//
//  MBDSettingViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/20.
//

import Foundation
import UIKit
import YYText
import Toast_Swift
import LGAlertView

class MBDSettingViewController : MBDBaseViewController {
    
    var tableView: UITableView!
    var settingItems : NSArray!
    var viewModel : MBDSettingViewModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "设置"
        viewModel = MBDSettingViewModel()
        
        let everyItemReactNative = ["title":"React Native 演示","accessable":true,"iconName":"about"] as [String : Any]
        let everyItemAbout = ["title":"关于","accessable":true,"iconName":"about"] as [String : Any]
        let everyItemLogout = ["title":"退出登录","accessable":false,"iconName":"logout"] as [String : Any]
        let everyItemWriteoff = ["title":"注销账号","accessable":false,"iconName":"ico_writeoff"] as [String : Any]

        if(MBDUserCenter.shared.userInfoFetched) {
            settingItems = [everyItemReactNative,everyItemAbout,everyItemLogout,everyItemWriteoff]
        } else {
            settingItems = [everyItemReactNative,everyItemAbout,everyItemWriteoff]
        }
        
        tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 100

        tableView.register(MBDIconTitleCommonCell.self, forCellReuseIdentifier: "MBDIconTitleCommonCell")
        
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
    }
    
    override func updateColors() {
        self.view.setDynamicBackgroundColor()
        tableView.setDynamicBackgroundColor()
        self.tableView.reloadData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if traitCollection.userInterfaceStyle == .dark {
            return .lightContent  // 暗黑模式下，状态栏文字为白色
        } else {
            if #available(iOS 13.0, *) {
                return .darkContent
            } else {
                // Fallback on earlier versions
                return .default
            }   // 浅色模式下，状态栏文字为黑色 (iOS 13 及之后)
            
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return false
    }
    
}


extension MBDSettingViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.settingItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "MBDIconTitleCommonCell", for: indexPath)
        let item = self.settingItems[indexPath.row] as! Dictionary<String, Any>
        (cell as! MBDIconTitleCommonCell ).title = item["title"] as! String
        (cell as! MBDIconTitleCommonCell ).accessable = item["accessable"] as! Bool
        let icon = UIImage(named: item["iconName"] as! String)
        (cell as! MBDIconTitleCommonCell).icon = icon

        if(0 == indexPath.row) {
            (cell as! MBDIconTitleCommonCell ).location = .top
        }
        if(self.settingItems.count - 1 == indexPath.row) {
            (cell as! MBDIconTitleCommonCell ).location = .bottom
        }
        
        
        return cell
    }
}


extension MBDSettingViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = self.settingItems[indexPath.row] as! Dictionary<String, Any>
        let title = item["title"] as! String
        if(title == "React Native 演示") {
            let vc = MBDReactNativeViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if(title == "退出登录") {
            MBDAccountInfoModel.clear()
            MBDUserCenter.shared.token = ""
            self.view.makeToast("登出成功")
        } else if (title == "关于") {

            let vc = MBDAboutViewController()
            self.navigationController?.pushViewController(vc, animated: true)

        } else if (title == "注销账号") {
            let alert = LGAlertView(title: nil, message: "注销账号会清空账号的所有信息，确定注销吗？", style: .alert, buttonTitles: ["确认"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {alert,index, title in
                //解锁
                self.startIndicatorAnimating()
                
                self.viewModel.doWriteOff { error in
                    self.stopIndicatorAnimationg()
                    
                    if nil != error {
                        self.view.makeToast(error?.localizedDescription)
                    } else {
                        self.view.makeToast("期待您再次使用群管家，再见！")
                        MBDUserCenter.shared.token = ""
                        MBDAccountInfoModel.clear()
                    }
                }
                
            }, cancelHandler: { alertView in
                
            })
            alert.show()
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
}
